package com.hilihili.util;

import sun.misc.BASE64Decoder;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @Author xhc
 * @Date 2024/2/2 21:32
 * @Version 1.0
 */
public class PictureMD5Util {
    private static String baseBase64 = "";

    public static String getBaseBase64() {
        return baseBase64;
    }


    public static byte[] getByte(String name) {
        // 得到文件长度
        File file = new File(name);
        byte[] b = new byte[(int) file.length()];
        try {
            InputStream in = new FileInputStream(file);
            try {
                in.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return b;
    }

    public static String md5(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            return new String(md.digest(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Boolean generatePicture(String imgBase64,String path){
        String result = imgBase64.substring(22);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(result);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String convertImageToBase64(String filePath){
        String base64Image = "";
        try {
            File file = new File(filePath);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] imageData = new byte[(int)file.length()];
            inputStream.read(imageData);
            base64Image = Base64.getEncoder().encodeToString(imageData);
            inputStream.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return "data:image/png;base64,"+base64Image;
    }
}
